package com.bootdo.clouddo.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.clouddo.config.JianshuApiConfig;
import com.bootdo.clouddo.config.JuejinApiConfig;
import com.bootdo.clouddo.config.TaskConfig;
import com.bootdo.clouddo.domain.juejin.*;
import com.bootdo.clouddo.service.juejin.*;
import com.bootdo.clouddo.utils.StringUtils;
import com.bootdo.clouddo.utils.http.JuejinUtils;
import com.google.gson.JsonObject;
import javafx.geometry.Pos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class JianshuPostTask {

    private static final Logger logger = LoggerFactory.getLogger(JianshuPostTask.class);
    
    private Map<String, String> param = new HashMap<>();
    
    
    @Autowired
    private IPostService postService;
    
    @Autowired
    private ITagService tagService;
    
    @Autowired
    private IJuejinUserService userService;
    
    @Autowired
    private ICategoryService categoryService;
    
    @Autowired
    private IPostDetailService detailService;
    
    @Value("${juejin.email}")
    private String email;
    
    @Value("${juejin.password}")
    private String password;

	@Async("myExecutor")
	@Scheduled(fixedRate = 60000)
    public void hostSocket() {
    	//拉取文章列表-时间线
    	String before = "";
    	for (int i = 0; i < 100; i++) {
			try {
				Thread.sleep(60);
				getHot(i);
			}catch (Exception e){
				e.printStackTrace();
			}
		}
    	
    }
    
    public void getHot(int page) throws InterruptedException{
    	Map<String, String> params = new LinkedHashMap<>();
    	
	    //发送Post数据并返回数据
	    JSONArray resultVo = JuejinUtils.getRequestForJSONArray(JianshuApiConfig.HOT_RECOMMENT + "?page=" + page, params);
	    
	    if(resultVo == null)
	    	return;
	    if(resultVo == null || resultVo.isEmpty())
	    	return;
	    
	    for (Object obj : resultVo) {
			JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(obj));
			json = json.getJSONObject("object").getJSONObject("data");
			if(json == null) {
				continue;
			}
	    	//获取postId
			PostDO post = savePost(json);
	    	if(post != null) {
	    		//saveTag(post);
	    		//saveCategory(post);
	    		//savePostDetail(post);
	    		//saveUser(post);
	    		logger.info("成功拉取一条数据:" + JSONObject.toJSONString(post));
	    	}
		}
    }
    
    private PostDO savePost(JSONObject obj) {
    	try {
			PostDO post = new PostDO();
			post.setId(obj.getString("slug"));
			post.setSummaryInfo(obj.getString("public_abbr"));

    		if(postService.exists(post.getId())) {
    			//logger.info("发现重复数据:" + post.getId());
    			// System.out.print(".");
    			return null;
    		}
    		//生成用户ID
    		post.setUserId(obj.getJSONObject("user").getString("slug"));
    		//生成categoryIds
    		post.setCategoryId("11");

    		JSONObject jo = JuejinUtils.getRequestForJSONObject(JianshuApiConfig.DETAIL_DATA + post.getId(), new HashMap<>());
			if(jo == null) {
				return null;
			}
			JSONObject user = jo.getJSONObject("user");
			user.put("avatarLarge", user.getString("avatar"));
			user.remove("avatar");
			user.put("username", user.getString("nickname"));
			user.remove("nickname");

			post.setSummaryInfo(jo.getString("description"));
			post.setTitle(jo.getString("public_title"));
			post.setUser(JSONObject.toJSONString(user));
			post.setUserId(user.getString("slug"));
			post.setAuthor(user.getString("nickname"));
			post.setBuildTime(new Date());
			post.setScreenshot(jo.getString("share_image_url"));
			post.setContent(obj.getString("public_abbr"));
			post.setCollectionCount(jo.getInteger("likes_count"));
			post.setCommentsCount(jo.getInteger("public_comment_count"));
			post.setCheckStatus(true);
			post.setUpdatedAt(new SimpleDateFormat( "yyyy-MM-dd HH:mm:sss" ).format(jo.getLong("last_updated_at")*1000));
			post.setType("post");
			postService.save(post);

			savePostDetail(jo);
			saveUser(user);
			return post;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    }
    
    private void savePostDetail(JSONObject jo) {
    	try {
    		if(detailService.get(jo.getString("slug")) != null)
    			return;
    		Map<String, String> p = new HashMap<>();

    		PostDetailDO detail = new PostDetailDO();
    		detail.setId(jo.getString("slug"));
    		detail.setContent(jo.getString("free_content"));
    		detail.setContent(detail.getContent().replaceAll("data-original-src=\\\"//upload-images.jianshu.io", "src=\\\"https://upload-images.jianshu.io"));
    		detail.setCreatedAt(jo.getString("first_shared_at"));
    		detail.setEntryId(jo.getString("id"));
			detail.setUpdatedAt(new SimpleDateFormat( "yyyy-MM-dd HH:mm:sss" ).format(jo.getLong("last_updated_at")*1000));
    		detailService.save(detail);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    /**
     * 获取用户信息
     * @param jo
     * @return
     */
    public UserDO saveUser(JSONObject jo) {
    	UserDO user = null;
    	try {
	    	user = new UserDO();
		    user.setId(jo.getString("slug"));
		    user.setAvatarLarge(jo.getString("avatar"));
		    user.setUsername(jo.getString("username"));
		    user.setJobTitle(jo.getString("-"));
		    user.setObjectId(jo.getString("id"));
		    user.setUpdatedAt(new SimpleDateFormat("yyyy-MM-dd HH:mm:sss").format(new Date()));
		    user.setAvatarLarge(jo.getString("avatarLarge"));
		    user.setSelfDescription(jo.getOrDefault("intro", "-").toString());
		    if(userService.get(user.getId()) == null)
		    	userService.save(user);
    	} catch (Exception e) {
			e.printStackTrace();
		}
	    return user;
    }
}
